package com.miplus.ccrm.core.service.sto;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.miplus.ccrm.core.mapper.PlRsReturnSoundRecordMapper;
import com.miplus.ccrm.core.mapper.TRecorderMapper;
import com.miplus.ccrm.core.pojo.PlRsReturnSoundRecord;
import com.miplus.ccrm.core.pojo.TRecorder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

@Slf4j
@Service
public class ImgService {

    @Resource
    TRecorderMapper tRecorderMapper;

    @Resource
    PlRsReturnSoundRecordMapper rsReturnSoundRecordMapper;

    public void OnPlayFileImg(String skyid, String ide,HttpServletResponse response){
        if(ide==null){
            ide="1";
        }
        String url=null;
        if("1".equals(ide)){
            // ndcs录音文件
            List<TRecorder> recList= tRecorderMapper.selectList(new QueryWrapper<TRecorder>()
                    .eq("callid",skyid)
                    .orderByDesc("recorderid")
            );
            if(recList==null){
                url="-1";
            }
            url=recList.get(0).getInfofileurl();
        }
        if("2".equals(ide)){
            // 荣数催记历史
            List<PlRsReturnSoundRecord> rsList = rsReturnSoundRecordMapper.selectList(new QueryWrapper<PlRsReturnSoundRecord>()
                    .eq("action_id", skyid));
            if(rsList==null){
                url="-1";
            }
            url=rsList.get(0).getUrl();
        }

        try {
            log.info("OnPlayFileImgRecord:{}",url);
            HttpResponse<InputStream> inputResponse = Unirest.get(url).asBinary();
            InputStream fis = inputResponse.getBody();
            response.addHeader("Content-Type","audio/mpeg;charset=utf-8");
            ServletOutputStream out = response.getOutputStream();
            int len_l = 0,totalcnt=0;
            byte[] buf = new byte[1024];
            while ((len_l = fis.read(buf)) != -1) {
                totalcnt+=len_l;
                out.write(buf, 0, len_l);
            }
            out.flush();
            out.close();
            fis.close();

            log.info("OnPlayFileImgRecord.totalcnt={}",totalcnt);
        } catch (Exception e) {
            log.error("OnPlayFileImgRecord.Err:",e);
        }
    }
}
